﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using SHDocVw;
using Microsoft.Win32;
using MessageBox = System.Windows.Forms.MessageBox;



namespace Piao
{

    [ComVisible(true),
    ClassInterface(ClassInterfaceType.None)]
#if DEBUG
    [Guid("09CAED01-0EA4-4A24-BDCE-3CD5EB8476B8")]
#else
    [Guid("08BE7563-A171-4B63-9C58-1FA611E54A89")]
#endif

    public class BHO : IObjectWithSite
    {
        WebBrowser browser;
        MainForm form = new MainForm();

        #region IObjectWithSite Members

        int IObjectWithSite.SetSite(object site)
        {

            if (null != site)
            {
                browser = site as WebBrowser;
                browser.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(browser_BeforeNavigate2);
            }
            else
                browser = null;

            return 0;
        }

        void browser_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
        {
            //ONLY ALLOW SINGLE WINDOW FOR USER
            int count = 0;
            MainForm.EnumDesktopWindowsDelegate enumrateDel = delegate(IntPtr hWnd, int lParam)
            {
                StringBuilder sb = new StringBuilder(256);
                MainForm.GetWindowText(hWnd, sb, 255);
                if (sb.ToString() == MainForm.FORM_UNIQUE_Name && MainForm.IsWindow(hWnd))
                {
                    count++;
                }

                return true;
            };

            MainForm.EnumDesktopWindows(IntPtr.Zero, enumrateDel, IntPtr.Zero);


            if (!string.IsNullOrEmpty(URL as string)
                && URL.ToString().Contains("12306")
                && count == 0
                )
                MainForm.Instance.Show();
        }


        int IObjectWithSite.GetSite(ref Guid riid, out IntPtr ppvSite)
        {
            IntPtr hwnd = Marshal.GetIUnknownForObject(browser);
            int hresult = Marshal.QueryInterface(hwnd, ref riid, out ppvSite);
            Marshal.Release(hwnd);

            return hresult;
        }


        #endregion

        [ComRegisterFunction]
        public static void Register(Type t)
        {
            RegisterHelper(t, true);
        }

        [ComUnregisterFunction]
        public static void Unregister(Type t)
        {
            RegisterHelper(t, false);
        }


        private static void RegisterHelper(Type t, bool trueForRegister)
        {
            const string path = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects";
            RegistryKey key = Registry.LocalMachine.OpenSubKey(path, true);

            string guid = t.GUID.ToString("B").ToUpper();

            if (trueForRegister)
            {
                RegistryKey bho = null;
                if ((bho = key.OpenSubKey(guid, true)) == null)
                    bho = key.CreateSubKey(guid);
                bho.SetValue("NoExplorer", 1, RegistryValueKind.DWord);
                bho.SetValue("", "12306 TICKET SEARCH");
            }
            else
            {
                key.DeleteSubKey(guid, false);
            }

            key.Close();
        }
    }


    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]
    //http://msdn.microsoft.com/en-us/library/windows/desktop/ms693765(v=vs.85).aspx
    public interface IObjectWithSite
    {
        [PreserveSig]
        int SetSite([MarshalAs(UnmanagedType.IUnknown)] object site);
        [PreserveSig]
        int GetSite(ref Guid riid, out IntPtr ppvSite);
    }


}
